import {
  BadRequestException,
  Body,
  Controller,
  Get,
  Inject,
  Post,
  Query,
} from '@nestjs/common';
import { UserService } from './user.service';
import { RegisterUserDto } from './dto/register-user.dto';
import { EmailService } from 'src/email/email.service';
import { RedisService } from 'src/redis/redis.service';
import { LoginUserDto } from './dto/login-user.dto';
import { JwtService } from '@nestjs/jwt';
import { RequireLogin, UserInfo } from 'src/custom.decorator';
import { UpdateUserPasswordDto } from './dto/update-user-password.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { ConfigService } from '@nestjs/config';
import { RegisterCaptchaDto } from './dto/register-captcha.dto';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}
  @Inject(RedisService) private redisService: RedisService;
  @Inject(EmailService) private emailService: EmailService;
  @Inject(JwtService) private jwtService: JwtService;
  @Inject(ConfigService)
  private configService: ConfigService;
  @Post('register')
  async register(@Body() registerUser: RegisterUserDto) {
    return await this.userService.register(registerUser);
  }

  @Get('register-captcha')
  async captcha(@Query() registerQuery: RegisterCaptchaDto) {
    const { address } = registerQuery;
    const code = Math.random().toString().slice(2, 8);
    await this.redisService.set(`captcha_${address}`, code, 5 * 60);
    await this.emailService.sendMail({
      to: address,
      subject: `注册验证码 ${code}`,
      html: `<p>您的验证码是：${code}</p>`,
    });
    return { message: '发送成功' };
  }

  @Get('send-user-login-captcha')
  async sendUserLoginCaptcha(@Query('username') username: string) {
    const user = await this.userService.findUserByUsername(username);
    if (!user) {
      throw new BadRequestException('用户不存在');
    }
    const code = Math.random().toString().slice(2, 8);
    await this.redisService.set(
      `user_login_captcha_${user.email}`,
      code,
      5 * 60,
    );
    await this.emailService.sendMail({
      to: user.email,
      subject: `登录验证码 ${code}`,
      html: `<p>您的验证码是：${code}</p>`,
    });
    return { message: '已发送验证码至注册邮箱，三分钟内有效!' };
  }

  @Post('login')
  async userLogin(@Body() loginUser: LoginUserDto) {
    const user = await this.userService.login(loginUser);
    return {
      data: {
        user,
        token: this.jwtService.sign(
          {
            userId: user.id,
            username: user.username,
          },
          {
            expiresIn:
              this.configService.get('jwt_access_token_expires_time') || '7d',
          },
        ),
      },
    };
  }

  @Get('info')
  @RequireLogin()
  async info(@UserInfo('userId') userId: number) {
    return this.userService.findUserDetailById(userId);
  }

  @Post('update_password')
  async updatePassword(@Body() passwordDto: UpdateUserPasswordDto) {
    return this.userService.updatePassword(passwordDto);
  }

  @Get('update_password/captcha')
  async updatePasswordCaptcha(@Query('address') address: string) {
    if (!address) {
      throw new BadRequestException('邮箱地址不能为空');
    }
    const code = Math.random().toString().slice(2, 8);

    await this.redisService.set(
      `update_password_captcha_${address}`,
      code,
      10 * 60,
    );

    await this.emailService.sendMail({
      to: address,
      subject: `更改密码验证码${code}`,
      html: `<p>你的更改密码验证码是 ${code}</p>`,
    });
    return '发送成功';
  }

  @Get('update/captcha')
  @RequireLogin()
  async updateCaptcha(@UserInfo('userId') userId: number) {
    const { email: address } =
      await this.userService.findUserDetailById(userId);
    const code = Math.random().toString().slice(2, 8);
    await this.redisService.set(
      `update_user_captcha_${address}`,
      code,
      10 * 60,
    );

    await this.emailService.sendMail({
      to: address,
      subject: `修改用户信息验证码 ${code}`,
      html: `<p>您的验证码是：${code}</p>`,
    });
    return '发送成功';
  }

  @Post('update')
  @RequireLogin()
  async update(
    @UserInfo('userId') userId: number,
    @Body() updateUserDto: UpdateUserDto,
  ) {
    return this.userService.update(userId, updateUserDto);
  }

  // @Post('upload')
  // @UseInterceptors(
  //   FileInterceptor('file', {
  //     dest: 'uploads',
  //     storage: storage,
  //     limits: {
  //       fileSize: 1024 * 1024 * 3,
  //     },
  //     fileFilter(req, file, callback) {
  //       const extname = path.extname(file.originalname);
  //       if (['.png', '.jpg', '.gif', '.jpeg', '.webp'].includes(extname)) {
  //         callback(null, true);
  //       } else {
  //         callback(new BadRequestException('只能上传图片'), false);
  //       }
  //     },
  //   }),
  // )
  // uploadFile(@UploadedFile() file: Express.Multer.File) {
  //   return this.configService.get('static_prefix')+file.path;
  // }
}
